package com.github.thinwonton.spring.showcase.hibernatevalidator.web.controller;

import com.github.thinwonton.spring.showcase.hibernatevalidator.entity.ValidateModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping(value = "/validate")
public class ValidateController {

    @RequestMapping(value = "/form", method = {RequestMethod.GET})
    public String showForm(Model model) {

        //表单必须有名字为contentModel的对象，否则报错
        if (!model.containsAttribute("contentModel")) {
            model.addAttribute("contentModel", new ValidateModel());
        }
        return "validateform";
    }

    @RequestMapping(value = "/action", method = {RequestMethod.POST})
    public String action(Model model,
                         @Valid @ModelAttribute("contentModel") ValidateModel validateModel,
                         BindingResult result) throws NoSuchAlgorithmException {

        //如果有验证错误 返回到form页面
        if (result.hasErrors()) {
            return showForm(model);
        }
        return "validatesuccess";
    }

}